using System.Text;
using Fiddler;

namespace WCATScenarioGenerator
{
    public static class Extensions
    {


        public static string GetPartOrDefault(this string[] original,int part, string defaultValue)
        {
            return original.Length <= part ? defaultValue : (original[part]);
        }

        public static string toWCATRequest(this Session session)
        {
            var result = new StringBuilder();
            result.AppendLine("\t\trequest {");
            result.AppendFormat("\t\t\tid = \"{0}\";\r\n", session.id);
            result.AppendFormat("\t\t\turl = \"{0}\";\r\n", session.oRequest.headers.RequestPath);

            result.AppendFormat("\t\t\tverb = {0};\r\n", session.oRequest.headers.HTTPMethod);
            if (session.oRequest.headers.HTTPMethod == "POST")
            {            
                result.AppendFormat("\t\t\tpostdata = \"{0}\";\r\n",new ASCIIEncoding().GetString ( session.requestBodyBytes));
            }

            result.AppendFormat("\t\t\tcookies = {0};\r\n", true);
            result.AppendFormat("\t\t\tsecure = {0};\r\n", session.isHTTPS);

            result.AppendFormat("\t\t\tstatuscode = {0};\r\n", session.responseCode);            
            // add headers
            foreach (Fiddler.HTTPHeaderItem header in session.oRequest.headers)
            {
                result.AppendLine("\t\t\tsetheader {");
                result.AppendFormat("\t\t\t\tname = \"{0}\";\r\n\t\t\t\tvalue = \"{1}\";\r\n", header.Name, header.Value);
                result.AppendLine("\t\t\t}");
            }
            result.AppendLine("\t\t}");

            return result.ToString(); 
        }
    }
}